import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class ShiroTest {
    private static final transient Logger log= LoggerFactory.getLogger(ShiroTest.class);

    public static void main(String[] args) {
        System.out.println(ShiroTest.class.getClassLoader().getResource("shiro.ini").getPath());
//        创建管理器工厂
        Factory<SecurityManager> factory=new IniSecurityManagerFactory("classpath:shiro.ini");
//        解析配置文件，并返回SecurityManager
        SecurityManager securityManager=factory.getInstance();
        //放入secu
        SecurityUtils.setSecurityManager(securityManager);
        //安全操作subject
        Subject currentUser=SecurityUtils.getSubject();

        Session session=currentUser.getSession();
//        放入Key
        session.setAttribute("someKey","aValue");
        String value=(String)session.getAttribute("someKey");
        if ("aValue".equals(value)){
            log.info("检索到正确的值");
        }
        //尝试登录用户
        if(!currentUser.isAuthenticated()){
            UsernamePasswordToken token=new UsernamePasswordToken("root","secret");
            token.setRememberMe(true);
            try {
                currentUser.login(token);
                if (currentUser.hasRole("admin")){
                    log.info("admin");
                }else {
                    log.info("not admin");
                }
                //查看角色
                if (currentUser.hasRole("role1")){
                    log.info("role1");
                }else {
                    log.info("not role1");
                }
                //查看用户是否有某个权限
                if (currentUser.isPermitted("perm1")){
                    log.info("perm1");
                }else {
                    log.info("not perm1");
                }
                currentUser.logout();
            } catch (AuthenticationException e) {
                e.printStackTrace();
            }

        }
    }
}
